package com.lsj.jsonLoin.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lsj.jsonLoin.entity.RespBean;
import com.lsj.jsonLoin.filter.LoginFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.*;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    PasswordEncoder passwordEncoder(){
        return NoOpPasswordEncoder.getInstance();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("lsj").password("123456").roles("admin")
                .and()
                .withUser(("cyb")).password("123456").roles("user");
    }


    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/vercode");//放行验证码请求
    }

    @Bean
    LoginFilter loginFilter() throws Exception {
        /*加载LoginFilterBean，并重写登录返回的数据为json格式
        * 之所以在这里进行重写，其原理就是实际进行登录认证的就是使用LoginFilter，该Filter加在UsernamePasswordAuthenticationFilter之前
        * 在formLogin中的表单配置就已经失效了，所以需要在注入该bean同时重写
        * */
        LoginFilter loginFilter = new LoginFilter();
        loginFilter.setAuthenticationSuccessHandler(new AuthenticationSuccessHandler() {
            @Override
            public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException {
                resp.setContentType("application/json;charset=utf-8");
                PrintWriter writer = resp.getWriter();
                Object principal = authentication.getPrincipal();
                RespBean respBean = RespBean.ok("登录成功", principal);
                ObjectMapper om = new ObjectMapper();
                String result = om.writeValueAsString(respBean);
                writer.write(result);
                writer.flush();
                writer.close();
            }
        });
        loginFilter.setAuthenticationFailureHandler(new AuthenticationFailureHandler() {
            @Override
            public void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse resp, AuthenticationException exception) throws IOException, ServletException {
                resp.setContentType("application/json;charset=utf-8");
                PrintWriter writer = resp.getWriter();
                RespBean respBean = RespBean.error(exception.getMessage());
                if (exception instanceof LockedException) {
                    respBean.setMsg("账户被锁定，请联系管理员!");
                } else if (exception instanceof CredentialsExpiredException) {
                    respBean.setMsg("密码过期，请联系管理员!");
                } else if (exception instanceof AccountExpiredException) {
                    respBean.setMsg("账户过期，请联系管理员!");
                } else if (exception instanceof DisabledException) {
                    respBean.setMsg("账户被禁用，请联系管理员!");
                } else if (exception instanceof BadCredentialsException) {
                    respBean.setMsg("用户名或者密码输入错误，请重新输入!");
                }
                ObjectMapper om = new ObjectMapper();
                String result = om.writeValueAsString(respBean);
                writer.write(result);
                writer.flush();
                writer.close();
            }
        });
        loginFilter.setAuthenticationManager(authenticationManager());//设置认证管理器，里面会用到
        loginFilter.setFilterProcessesUrl("/doLogin");
        return loginFilter;
    }


    /*使用postman工具验证json格式登录,使用/login.html验证页面的form表单登录*/
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.addFilterAt(loginFilter(), UsernamePasswordAuthenticationFilter.class);//设置自定义的登录认证
        http.authorizeRequests()
                .antMatchers("/admin/**").hasRole("admin")
                .antMatchers("/user/**").hasRole("user")
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login.html")
                .loginProcessingUrl("/doLogin")
                .defaultSuccessUrl("/hello")
                .permitAll()
                .and()
                .csrf()
                .disable()
                .exceptionHandling()
                //没有登录时，在这里处理结果，返回json格式数据，否则会执行默认的实现类，返回登录页面
                .authenticationEntryPoint(new AuthenticationEntryPoint() {
                    @Override
                    public void commence(HttpServletRequest req, HttpServletResponse resp, AuthenticationException authException) throws IOException, ServletException {
                        resp.setContentType("application/json;charset=utf-8");
                        PrintWriter writer = resp.getWriter();
                        RespBean respBean = RespBean.error("访问失败");
                        ObjectMapper om = new ObjectMapper();
                        String result = om.writeValueAsString(respBean);
                        writer.write(result);
                        writer.flush();
                        writer.close();
                    }
                });
    }
}
